<?php
namespace backend\controllers;
use common\models\Base;
use Yii;
use backend\models\User;
use backend\models\UserSearch;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\filters\VerbFilter;
use backend\models\ActionLog;
use c006\alerts\Alerts;
use common\models\Department;
use backend\components\MyTrait;
use common\helpers\MyHelper;
/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@']
                    ]
                ]
            ],
        ];
    }
    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        if(!Yii::$app->user->can('user/index')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));
		
		$searchModel = new UserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $arrayStatus = User::getArrayStatus();

        $Department = Department::getTree(0, Department::find()->asArray()->all());

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'arrayStatus' => $arrayStatus,
            'department' => $Department,
        ]);
    }
    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($auth_key)
    {
        if(!Yii::$app->user->can('user/view')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));
        $id = MyTrait::getId('User',$auth_key);
		return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }
    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        if(!Yii::$app->user->can('user/create')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));
		
		$model = new User(['scenario' => 'admin-create']);
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $post = Yii::$app->request->post();
            $roles = $post['User']['role'];
            $model->role = is_array($roles) ? implode(',',$roles) : null;
            if($model->save()){
                //Yii::$app->authManager->assign(Yii::$app->authManager->getRole($model->role), $model->id);
                if(!empty($roles) && is_array($roles)){
                    foreach($roles as $item){
                        Yii::$app->authManager->assign(Yii::$app->authManager->getRole($item), $model->id);
                    }
                }
                return $this->redirect(['index']);
            }

        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($auth_key)
    {
        if(!Yii::$app->user->can('user/update')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));
        $id = MyTrait::getId('User',$auth_key);
		$model = $this->findModel($id);
        $model->setScenario('admin-update');
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $post = Yii::$app->request->post();
            $roles = $post['User']['role'];
            $model->role = is_array($roles) ? implode(',',$roles) : null;
            if($model->save()){
                Yii::$app->authManager->revokeAll($id);
                if(!empty($roles) && is_array($roles)){
                    foreach($roles as $item){
                        Yii::$app->authManager->assign(Yii::$app->authManager->getRole($item), $id);
                    }
                }
                return $this->redirect(['index']);
            }
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($auth_key)
    {
        $id = MyTrait::getId('User',$auth_key);
        if(!Yii::$app->user->can('user/delete')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));
        Yii::$app->authManager->revokeAll($id);
		$this->findModel($id)->delete();
        return $this->redirect(['index']);
    }
    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionPassword()
    {

        $id = Yii::$app->user->id;
        $model = $this->findModel($id);
        $model->setScenario('admin-password');
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->authManager->revokeAll($id);
            Yii::$app->authManager->assign(Yii::$app->authManager->getRole($model->role), $id);
            Alerts::setMessage("密码更新成功");
            Alerts::setAlertType(Alerts::ALERT_SUCCESS);
            ActionLog::log(Yii::t('app', 'Change Password'));
            return $this->redirect(['password']);
        } else {
            //print_r($model->errors);exit;
            return $this->render('password', [
                'model' => $model,
            ]);
        }
    }

    public function actionLayer(){

        $this->layout = 'layer';

        $object_id = Yii::$app->request->get('object_id');
        $Department = Department::getTree(0, Department::find()->where(['organization_id'=>Yii::$app->user->identity->organization_id])->asArray()->all());
        $searchModel = new UserSearch();
        //print_r(Yii::$app->request->queryParams);
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('layer', [
            'object_id' => $object_id,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'department' => $Department,
        ]);
    }

    public function actionDialog(){

        $this->layout = 'dialog';

        $object_id = Yii::$app->request->get('object_id');
        $departmentTree = MyHelper::list_to_tree(Department::find()->select(['id','parent_id','name'])->where(['organization_id'=>Yii::$app->user->identity->organization_id])->orderBy('sort ASC')->asArray()->all());
        $departmentTreeMenu = MyHelper::popup_tree_menu($departmentTree);
        //print_r($departmentTreeMenu);
        return $this->render('dialog', [
            'object_id' => $object_id,
            'departmentTreeMenu' => $departmentTreeMenu,
        ]);
    }


}